/*
 * @Date: 2023-02-15 16:00:15
 * @LastEditTime: 2023-03-03 13:17:19
 * @FilePath: /hash-guess-game/src/store/useSysStore.ts
 * 介绍:系统缓存仓库
 */
import { defineStore } from "pinia";
import { apiLogin, Login } from "@@/api/module/sys";
import { sdkConnect, sdkWalletInfo } from "@@/sdk/solana";
import { resetStore } from "@@/hooks/reset";
import { getCurrentHrefQueryParam } from "@@/utils/tools/tools";
import toast from "@@/components/rework/toast";

export default defineStore("StoreSys", {
  //*全局仓库
  state: initState,
  //*全局函数
  actions: {
    async login(): Promise<boolean> {
      toast.loading();
      const connentRes = await sdkConnect();
      toast.close();
      if (!connentRes.status) {
        toast.error(connentRes.message);
        return false;
      }
      toast.loading();
      const walletInfo = await sdkWalletInfo();
      toast.close();
      if (!walletInfo.data) {
        resetStore();
        toast.error(walletInfo.message);
        return false;
      }
      const { accounts, ns } = walletInfo.data;
      const query = getCurrentHrefQueryParam();
      const params: Login.Req = {
        accounts,
        clientId: "99",
        chainId: 99,
        nwtworkId: "0",
        that_wallet_name: ns || "SOLANA",
        invit: query.invit,
      };
      if (
        this.lastLoginInfo?.accounts &&
        accounts &&
        this.lastLoginInfo.accounts === accounts
      ) {
        //*如果缓存数据等于当前获取到的数据则不获取token
        this.isLogin = true;
        return true;
      }
      //*登录服务器并获取token
      const res = await apiLogin(params);
      if (!res) {
        resetStore();
        return false;
      }
      this.$patch((state) => {
        state.lastLoginInfo = params;
        state.tokenInfo = res;
        state.isLogin = true;
      });
      return true;
    },
  },
  //*计算属性
  getters: {},
  //*仓库数据缓存
  persist: {
    enabled: true,
    strategies: [
      {
        key: "StoreSys",
        storage: localStorage, //指定储存位置
      },
    ],
  },
});
/**state类型定义 */
interface StoreSys {
  lastLoginInfo?: LastLoginInfo;
  tokenInfo?: Login.Res;
  isLogin: boolean;
  setting: Setting;
}
/**设置 */
export interface Setting {
  language: string;
}
interface LastLoginInfo extends Login.Req {}
/**初始化pinia */
function initState(): StoreSys {
  return {
    lastLoginInfo: undefined,
    tokenInfo: undefined,
    isLogin: false,
    setting: {
      language: "zh-CN",
    },
  };
}
